package me.maiz.babyisland.admin.asynctask;

import me.maiz.babyisland.admin.asynctask.event.ElasticSearchIndexEvent;
import me.maiz.babyisland.dao.model.Product;
import me.maiz.babyisland.es.ProductRepository;
import me.maiz.babyisland.es.entity.ProductDocument;
import com.google.common.eventbus.AllowConcurrentEvents;
import com.google.common.eventbus.AsyncEventBus;
import com.google.common.eventbus.Subscribe;
import lombok.extern.slf4j.Slf4j;
import me.maiz.babyisland.es.ProductRepository;
import me.maiz.babyisland.es.entity.ProductDocument;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.time.StopWatch;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;

@Component
@Slf4j
public class ElasticSearchIndexTask<T> {

    @Autowired
    private AsyncEventBus asyncEventBus;

    @Autowired
    private ProductRepository productRepository;


    @PostConstruct
    public void init(){
        asyncEventBus.register(this);
    }


    @Subscribe
    @AllowConcurrentEvents
    public void action(ElasticSearchIndexEvent<T> event) {
        StopWatch stopWatch = new StopWatch();
        log.info("同步数据到搜索引擎，{}",event);
        stopWatch.start();
        try {
            T data = event.getData();
            if(data instanceof Product){
                Product p = (Product) data;
                ProductDocument pd = new ProductDocument();
                BeanUtils.copyProperties(pd,p);
                pd.setId(p.getProductId());
                productRepository.save(pd);
            }

        }catch (Exception e){
            log.error("异步消息响应异常:",e);
        }finally {
            stopWatch.stop();
            log.info("同步数据到搜索引擎结束，耗时{}ms",stopWatch.getTime());
        }
    }


}
